// === 配置区 ===

// Home Assistant MQTT 配置
const char *MQTT_SERVER = "192.168.1.100"; // Home Assistant 局域网 IP
const int MQTT_PORT = 1883;                // MQTT 端口
const char *MQTT_USER = "";                // 无认证留空
const char *MQTT_PASSWORD = "";            // 无认证留空

// MQTT 主题
const char *MQTT_DATA_TOPIC = "homeassistant/esp8266/multi_data";                   // 数据发布主题
const char *AUTO_DISCOVERY_TEMP_TOPIC = "homeassistant/sensor/esp8266_temp/config"; // 温度自动发现主题
const char *AUTO_DISCOVERY_HUM_TOPIC = "homeassistant/sensor/esp8266_hum/config";   // 湿度自动发现主题

WiFiClient espClient;
PubSubClient mqttClient(espClient);

// === 数据生成与格式处理 ===
// 生成 10 组模拟数据（时间戳 + 温湿度）
String generateMultiData()
{
  String json = "{";
  json += "\"data_points\": [";
  for (int i = 0; i < 10; i++)
  {
    unsigned long timestamp = millis() / 1000 + i; // 模拟递增时间戳
    float temp = 25.0 + i * 0.1;                   // 温度 25.0~25.9
    float hum = 50.0 + i * 0.5;                    // 湿度 50.0~54.5
    json += "{";
    json += "\"timestamp\":" + String(timestamp) + ",";
    json += "\"temp\":" + String(temp, 1) + ",";
    json += "\"hum\":" + String(hum, 1) + "";
    json += "}";
    if (i < 9)
      json += ","; // 最后一组不加逗号
  }
  json += "]";
  json += "}";
  return json; // 返回完整 JSON 数据
}

// 发送自动发现配置（让 Home Assistant 识别数据字段）
void sendAutoDiscoveryConfig()
{
  // 温度传感器自动发现配置（提取第 1 组数据的温度）
  String tempConfig = String("{") +
                      "\"name\":\"ESP8266 温度\",\"device_class\":\"temperature\"," +
                      "\"state_topic\":\"" + MQTT_DATA_TOPIC + "\"," +
                      "\"value_template\":\"{{ value_json.data_points[0].temp }}\"," +
                      "\"unit_of_measurement\":\"°C\"," +
                      "\"unique_id\":\"esp8266_temp_sensor\"" +
                      "}";
  mqttClient.publish(AUTO_DISCOVERY_TEMP_TOPIC, tempConfig.c_str());

  // 湿度传感器自动发现配置（提取第 1 组数据的湿度）
  String humConfig = String("{") +
                     "\"name\":\"ESP8266 湿度\",\"device_class\":\"humidity\"," +
                     "\"state_topic\":\"" + MQTT_DATA_TOPIC + "\"," +
                     "\"value_template\":\"{{ value_json.data_points[0].hum }}\"," +
                     "\"unit_of_measurement\":\"%\",\"unique_id\":\"esp8266_hum_sensor\"" +
                     "}";
  mqttClient.publish(AUTO_DISCOVERY_HUM_TOPIC, humConfig.c_str());
}

// === MQTT 连接与交互 ===
void setupMQTT()
{
  mqttClient.setServer(MQTT_SERVER, MQTT_PORT);
  mqttClient.setCallback([](char *topic, byte *payload, unsigned int length)
                         {
                           // 如需接收 Home Assistant 指令，可在此添加回调逻辑（本次仅发送数据，暂不处理）
                         });
}

bool connectMQTT()
{
  static String clientId = "ESP8266-MQTT-" + WiFi.macAddress();
  if (mqttClient.connect(clientId.c_str(), MQTT_USER, MQTT_PASSWORD))
  {
    Serial.println("MQTT 连接 Home Assistant 成功");
    sendAutoDiscoveryConfig(); // 连接后发送自动发现配置
    return true;
  }
  Serial.print("MQTT 连接失败，错误码：");
  Serial.print(mqttClient.state());
  return false;
}

//   setupMQTT();
//   if (!connectMQTT()) return;  // 确保 MQTT 连接

// void loop() {
//   if (!mqttClient.connected()) {
//     connectMQTT();  // 重连处理
//   }
//   mqttClient.loop();  // 处理 MQTT 消息

//   // 每 5 秒发送一次 10 组数据
//   static unsigned long lastSendTime = 0;
//   if (millis() - lastSendTime > 5000) {
//     lastSendTime = millis();
//     String data = generateMultiData();  // 生成 JSON 数据
//     if (mqttClient.publish(MQTT_DATA_TOPIC, data.c_str())) {
//       Serial.println("发送数据到 Home Assistant：\n" + data);
//     }
//   }
// }